#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
公共基础数据接口使用示例
"""

import os
import sys
import logging

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from jlpay.base.config import OrgConfig
from jlpay.services.base_data_service import BaseDataService
from jlpay.model.base_data import (
    BankListRequest, BankBranchListRequest, MccQueryRequest, 
    RegionListRequest, BankCardBinMatchingRequest
)
from jlpay.utils.log_config import configure_rotating_file_logging

# =================== 常量定义 =====================
# 日志配置常量
LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(filename)s:%(lineno)d - %(funcName)s() - %(message)s'
MAX_LOG_SIZE = 10 * 1024 * 1024  # 10MB
MAX_BACKUP_COUNT = 10

# =================== 日志配置 =====================
# 配置日志系统，使用滚动文件处理器
log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "logs")
root_logger = configure_rotating_file_logging(
    level=logging.INFO,
    log_dir=log_dir,
    log_name_prefix="jlpay",
    log_format=LOG_FORMAT,
    max_bytes=MAX_LOG_SIZE,
    backup_count=MAX_BACKUP_COUNT,
    propagate=True,
    module_levels={
        'jlpay.http': logging.INFO,
        'jlpay.service': logging.INFO,
        'examples': logging.INFO
    }
)

# 获取示例程序的logger实例
logger = logging.getLogger("examples.base_data")
logger.setLevel(logging.INFO)

# =================== 密钥配置 =====================
# SM2公私钥
sm2_public_key_pem = """-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEJJhFmjeMRp9GwShxtWunv6Wny//m
Dg2pcnu0llDQvIYo5O3R+al39NekciZ0BIrT21Y/QJrXgJIoyBr6STml6g==
-----END PUBLIC KEY-----"""

sm2_private_key_pem = """-----BEGIN EC PRIVATE KEY-----
MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgHqOp471SMDsQml2G
2ErpZPLD2X7rbMqa6P1O9Zqlhe+gCgYIKoEcz1UBgi2hRANCAAQkmEWaN4xGn0bB
KHG1a6e/pafL/+YODalye7SWUNC8hijk7dH5qXf016RyJnQEitPbVj9AmteAkijI
GvpJOaXq
-----END EC PRIVATE KEY-----"""

# 嘉联支付平台公钥
jlpay_pub_key_pem = """-----BEGIN PUBLIC KEY-----
MIIBMzCB7AYHKoZIzj0CATCB4AIBATAsBgcqhkjOPQEBAiEA/////v//////////
//////////8AAAAA//////////8wRAQg/////v////////////////////8AAAAA
//////////wEICjp+p6dn140TVqeS89lCafzl4n1FauPkt28vUFNlA6TBEEEMsSu
LB8ZgRlfmQRGajnJlI/jC7/yZgvhcVpFiTNMdMe8Nzai9PZ3nFm9zuNraSFT0KmH
fMYqR0AC3zLlITnwoAIhAP////7///////////////9yA99rIcYFK1O79Ak51UEj
AgEBA0IABKZ3VWwH0Aw9xvOWXb+xM2gXyApWEAZLFy8UyIigp3ehOTwPJ693njrg
NavTLdzAtFBqXRreivlwBTIFy8iRgn8=
-----END PUBLIC KEY-----"""

# =================== 工具函数 =====================
def create_config():
    """
    创建配置对象
    
    Returns:
        OrgConfig实例
    """
    config = OrgConfig.builder() \
        .app_id("1vzougr30f9vcw") \
        .url("https://openapi-uat.jlpay.com") \
        .org_pri_key(sm2_private_key_pem) \
        .org_pub_key(sm2_public_key_pem) \
        .jlpay_pub_key(jlpay_pub_key_pem) \
        .build()
    return config


def send_request_and_handle_response(service_method, operation_name, *args, **kwargs):
    """
    发送请求并处理响应
    
    Args:
        service_method: 服务方法
        operation_name: 操作名称
        *args: 位置参数
        **kwargs: 关键字参数
        
    Returns:
        响应对象
    """
    try:
        response = service_method(*args, **kwargs)
        
        if response.is_success():
            logger.info(f"{operation_name}成功")
            logger.info(f"响应报文：{response.to_dict()}")
        else:
            logger.error(f"{operation_name}失败: {response.ret_code} - {response.ret_msg}[{response.ret_code}]")
        
        return response
    except Exception as e:
        logger.error(f"{operation_name}失败: {str(e)}")
        raise


def base_data_demo():
    """
    公共基础数据接口示例
    """
    logger.info("开始执行公共基础数据接口示例")
    
    # 创建配置和服务
    config = create_config()
    service = BaseDataService(config)
    
    # 查询银行总行信息
    logger.info("=== 查询银行总行信息 ===")
    bank_list_request = BankListRequest()
    bank_list_request.set_bank_name("中国银行").set_limit(10).set_offset(0)
    send_request_and_handle_response(
        service.query_bank_list,
        "查询银行总行信息",
        bank_list_request
    )

    # 查询分支行信息
    logger.info("=== 查询分支行信息 ===")
    branch_list_request = BankBranchListRequest()
    branch_list_request.set_branch_name("深圳").set_limit(10).set_offset(0)
    send_request_and_handle_response(
        service.query_bank_branch_list,
        "查询分支行信息",
        branch_list_request
    )

    # 查询MCC信息
    logger.info("=== 查询MCC信息 ===")
    mcc_request = MccQueryRequest()
    mcc_request.set_mcc_code("5411").set_limit(10).set_offset(0)
    send_request_and_handle_response(
        service.query_mcc,
        "查询MCC信息",
        mcc_request
    )

    # 查询地区码信息
    logger.info("=== 查询地区码信息 ===")
    region_request = RegionListRequest()
    region_request.set_region_name("北京").set_region_rank("1").set_limit(10).set_offset(0)
    send_request_and_handle_response(
        service.query_region_list,
        "查询地区码信息",
        region_request
    )

    # 查询银行卡bin信息
    logger.info("=== 查询银行卡bin信息 ===")
    card_bin_request = BankCardBinMatchingRequest()
    card_bin_request.set_card_no("6217002990114156528")
    send_request_and_handle_response(
        service.query_bank_card_bin,
        "查询银行卡bin信息",
        card_bin_request
    )
    
    logger.info("公共基础数据接口示例执行完毕")


if __name__ == "__main__":
    logger.info("==================================================")
    logger.info("===== 公共基础数据接口示例 开始 =====")
    logger.info("==================================================")
    
    base_data_demo()
    
    logger.info("==================================================")
    logger.info("===== 公共基础数据接口示例执行完毕 =====")
    logger.info("==================================================") 